<?php
/**
 * 企业微信通讯录
 */
namespace app\wework\admin;

use app\system\admin\Admin;
use app\common\model\WeworkUser as WeworkUserModel;
use app\common\service\SystemUser as SystemUserService;
use think\Console;

class User extends Admin
{
    protected $hisiModel = 'WeworkUser';//模型名称[通用添加、修改专用]
    protected $hisiValidate = '';
    protected $hisiAddScene = '';//添加数据验证场景名
    protected $hisiEditScene = '';//更新数据验证场景名

    public function initialize() {
    	parent::initialize();

    	$this->assign('status', ['1'=>'已激活','2'=>'已禁用','4'=>'未激活','5'=>'退出企业']);
    	$this->assign('systemUserKV', (new SystemUserService())->getKVList(1));
    }

    public function index()
    {
    	if ($this->request->isAjax()) {
    		$where      = $data = [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$keyword    = $this->request->param('keyword/s');

    		$where    = [];
    		if ($keyword) {
    			$where[] = ['userid|name|mobile', 'like', "%{$keyword}%"];
    		}

    		$order = 'id desc';
    		$data['data'] = weworkusermodel::where($where)->page($page)->limit($limit)->order($order)->select();
    		$data['count'] = weworkusermodel::where($where)->count('id');
    		$data['code'] = 0;
    		$data['msg'] = '';
    		return json($data);
    	}

    	$assign = [];
    	return $this->assign($assign)->fetch();
    }

    /**
     * 同步企业微信用户
     *
     * @author KING
     * @date 2020年7月6日
     *
     * @return \think\response\Json
     */
    public function sync() {
    	$output = Console::call('cronSyncWeworkUser', ['--print=0']);
    	$res = json_decode($output->fetch(), true);
    	if ($res['code'] == 1) {
	    	$data['code'] = 1;
	    	$data['msg'] = '同步企业微信用户成功';
    	} else {
    		$data['code'] = 0;
    		$data['msg'] = '同步企业微信用户失败';
    	}
    	return json($data);
    }
}